package com.woniuxy.portal.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.common.consts.RedisConst;
import com.woniuxy.portal.model.entity.Book;
import com.woniuxy.portal.service.BookService;
import com.woniuxy.portal.mapper.BookMapper;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * @author HASEE
 * @description 针对表【t_book】的数据库操作Service实现
 * @createDate 2025-08-02 11:43:04
 */
@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book>
        implements BookService {

    /**
     * 查询销量排行榜图书列表
     *
     * @param pageNum  页码
     * @param pageSize 每页数量
     * @return IPage<Book> 图书分页结果，按购买数量降序排列
     */
    @Override
    @Cacheable(cacheNames = RedisConst.BOOK_LIST, keyGenerator = "keyGenerator")
    public IPage<Book> findTopSale(Integer pageNum, Integer pageSize) {

        // 构造查询条件，按购买数量降序排列
        Wrapper<Book> wrapper = Wrappers.lambdaQuery(Book.class).orderByDesc(Book::getBuyCount);
        // 执行分页查询
        return baseMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
    }

    /**
     * 根据图书类型分页查询图书信息
     *
     * @param pageNum  页码
     * @param pageSize 每页大小
     * @param typeId   图书类型ID
     * @return IPage<Book> 图书分页数据
     */
    @Override
    @Cacheable(cacheNames = RedisConst.BOOK_LIST, keyGenerator = "keyGenerator")
    public IPage<Book> findByType(Integer pageNum, Integer pageSize, Integer typeId) {

        // 构造查询条件：根据类型ID查询并按创建时间降序排列
        Wrapper<Book> wrapper = Wrappers.lambdaQuery(Book.class).eq(Book::getTypeId, typeId).orderByDesc(Book::getCreateTime);
        return baseMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
    }

    /**
     * 根据书籍ID查找书籍信息
     * 指定方法名指定参数：#root.methodName +':'+ #bookId
     * 通过 SpEL表达式 在注解内定义，适合简单的生成规则
     *
     * @param bookId 书籍ID，不能为空
     * @return Book 返回对应的书籍对象，如果未找到则返回null
     */
    @Override
//    @Cacheable(cacheNames = RedisConst.BOOK_DETAIL, keyGenerator = "keyGenerator")
    @Cacheable(cacheNames = RedisConst.BOOK_DETAIL, key = "#root.methodName +':'+ #bookId")
    public Book findById(Integer bookId) {
        return super.getById(bookId);
    }

}




